package db

import (
	"beego/comm/source"
	"fmt"

	"github.com/astaxie/beego"
	"github.com/gomodule/redigo/redis"
)

var (
	redisUrl string = fmt.Sprintf("%s:%s", source.Src.GetRedisInfo()["ip"], source.Src.GetRedisInfo()["port"])
	redisPwd string = source.Src.GetRedisInfo()["pwd"]
)

func getRedisDial() (redis.Conn, error) {
	setdb := redis.DialDatabase(0)
	setPasswd := redis.DialPassword(redisPwd)
	conn, err := redis.Dial("tcp", redisUrl, setdb, setPasswd)
	return conn, err
}

func RedisSet(key string, value string) (interface{}, error) {
	conn, err := getRedisDial()
	if nil != err {
		return nil, err
	}
	defer conn.Close()
	rev, err := conn.Do("set", key, value, "ex", 60*30)
	if nil != err {
		return nil, err
	}
	return rev, nil
}

func RedisDel(key string) (interface{}, error) {
	conn, err := getRedisDial()
	if nil != err {
		return nil, err
	}
	defer conn.Close()
	rev, err := conn.Do("del", key)
	if nil != err {
		return nil, err
	}
	return rev, nil
}

func RedisGet(key string) (string, error) {
	conn, err := getRedisDial()
	if nil != err {
		return "", err
	}
	defer conn.Close()
	value, err := conn.Do("get", key)
	if nil != err || nil == value {
		return "", err
	}
	return string(value.([]byte)), nil
}

func init() {
	beego.Info("测试连接redis...")
	conn, err := getRedisDial()
	if nil != err {
		panic(err)
	}
	conn.Close()
	beego.Info("redis连接测试完成")
}
